﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; 
using System.IO;
using Wedo.Mvc.Utility;
using Wedo.Recognition.Domain.Models;
using Wedo.Recognition.Web.Controllers;
using Wedo.Recognition.Service;
using Wedo.Mvc.Pager;
using Wedo.Recognition.Domain;
using Wedo.Recognition.Repository;

namespace Wedo.IPRP.Web.Controllers
{
    public class GenerateRecieveController : EntityController<GenerateRecieve, CommonTimeSearch>
    {
        private  RecieveService bdService;
        public GenerateRecieveController(IUnitWork dbContext)
            : base(dbContext)
        {
            bdService = new RecieveService(_dbContext);
        }
      
        public ActionResult DownloadFile(Guid ID)
        {
            var model = FindById(ID);
            string serverpath = model.GenerateRecieveFileName;
            if (System.IO.File.Exists(serverpath)==false)
            {
                throw  new Exception("没有此文件！") ;
            }
            string exten = System.IO.Path.GetExtension(model.GenerateRecieveFileName);
            string contenttype = "text/plain";
            switch (exten)
            {
                case ".pdf": contenttype = "application/pdf"; break;
                case ".xlsx": contenttype = "application/ms-excel"; break;
            }
            string filename = Request.Browser.Browser == "IE" ? Url.Encode(System.IO.Path.GetFileName(serverpath)) : System.IO.Path.GetFileName(serverpath);
            return File(serverpath, contenttype, filename);

        }

        protected override Wedo.Service.Common.IBaseService<GenerateRecieve> EntityService
        {
            get { return bdService; }
        }

        protected override PagedList<GenerateRecieve> GetSearchPagedList(CommonTimeSearch where)
        {
            where = where ?? new CommonTimeSearch();
            var query=EntityService.GetAll();
            if (where.Keyword.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.GenerateRecieveFileName.Contains(where.Keyword));
            }
            if (where.StartTime != null)
            {
                DateTime Start = where.StartTime.Value;
                query = query.Where(m => m.Created > Start);
            }
            if (where.EndTime != null)
            {
                DateTime endTime = where.EndTime.Value.AddDays(1);
                query = query.Where(m => m.Created < endTime);
            }

            return query.OrderByDescending(m => m.Created).ToPagedList(where.Page, 10);
        }
    }
}
